package wqh.controller;


import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import wqh.pojo.MapRet;
import wqh.service.AlarmEventConfirmService;
import wqh.service.AlarmEventService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/water/export")
public class ExportController {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(ExportController.class);

    @Autowired
    private AlarmEventService alarmEventService;

    @Autowired
    private AlarmEventConfirmService alarmEventConfirmService;

    @ResponseBody
    @RequestMapping(value = "/year",method = RequestMethod.GET)
    public Object yearExcel(HttpServletResponse response, @RequestParam(value = "year",required = true) int year)
    {
        try {
            List<Map<String,Object>> objectList = new ArrayList<Map<String, Object>>();
            for(int i = 1; i <= 12; i++){
                if( i % 2 != 0 && i < 9 || i % 2 == 0 && i >= 8){
                    String start = year + "-" + i + "-" + 1;
                    String end = year + "-" + i + "-" + 30;
                    objectList.add(getCountMap(i,start,end));
                }
                else if(i == 2){
                    String start = year + "-" + i + "-" + 1;
                    String end = null;
                    if(year % 4 == 0 && year % 100 != 0) end = year + "-" + i + "-" + 29;
                    else end = year + "-" + i + "-" + 28;
                    objectList.add(getCountMap(i,start,end));
                }
                else{
                    String start = year + "-" + i + "-" + 1;
                    String end = year + "-" + i + "-" + 29;
                    objectList.add(getCountMap(i,start,end));
                }
            }
            String[] columns = {"月份","报警数量","已确认","未处理","处理率"};
            HSSFWorkbook book = new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet();
            HSSFRow headRow = sheet.createRow(0);
            for(int i = 0; i < columns.length; i++){
                HSSFCell cell = headRow.createCell(i);
                cell.setCellValue(columns[i]);
                sheet.setColumnWidth(i,38*150);
            }
            for(int i = 1; i < objectList.size() + 1; i++){
                Map<String ,Object> map = objectList.get(i - 1);
                HSSFRow nextRow = sheet.createRow(i);
                HSSFCell cell = nextRow.createCell(0);
                cell.setCellValue(map.get("month").toString());
                cell = nextRow.createCell(1);
                cell.setCellValue(map.get("month_all").toString());
                cell = nextRow.createCell(2);
                cell.setCellValue(map.get("month_confirm").toString());
                cell = nextRow.createCell(3);
                cell.setCellValue(map.get("month_alarm").toString());
                cell = nextRow.createCell(4);
                cell.setCellValue(map.get("month_rate").toString());
            }
            String fileName = year+ "年份报警记录总览.xls";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            book.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName).getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buff = new byte[4096];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
            return MapRet.FILE_DOWNLOAD_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("年记录导出错误：" + e);
            return MapRet.FILE_DOWNLOAD_ERROR();
        }
    }

    @ResponseBody
    @RequestMapping(value = "/month",method = RequestMethod.GET)
    public Object monthExcel(HttpServletResponse response, @RequestParam(value = "year",required = true) int year_input, @RequestParam(value = "month",required = true) int month_input)
    {
        try {
            List<Map<String,Object>> objectList = new ArrayList<Map<String, Object>>();
            int monthLenght = 0;
            if( month_input % 2 != 0 && month_input < 9 || month_input % 2 == 0 && month_input >= 8){
                monthLenght = 31;
            }else if(month_input == 2){
                if(year_input % 4 == 0 && year_input % 100 != 0) monthLenght = 29;
                else monthLenght = 28;
            }else{
                monthLenght = 30;
            }
            for(int i = 1; i <= monthLenght; i++) {
                String start = year_input + "-" + month_input + "-" + i;
                String end = year_input + "-" + month_input + "-" + i;
                objectList.add(getCountMap2(year_input,month_input,i,start,end));
            }

            String[] columns = {"日期","报警数量","已确认","未处理"};
            HSSFWorkbook book = new HSSFWorkbook();
            HSSFSheet sheet = book.createSheet();
            HSSFRow headRow = sheet.createRow(0);
            for(int i = 0; i < columns.length; i++){
                HSSFCell cell = headRow.createCell(i);
                cell.setCellValue(columns[i]);
                sheet.setColumnWidth(i,38*150);
            }
            for(int i = 1; i < objectList.size() + 1; i++){
                Map<String ,Object> map = objectList.get(i - 1);
                HSSFRow nextRow = sheet.createRow(i);
                HSSFCell cell = nextRow.createCell(0);
                cell.setCellValue(map.get("day").toString());
                cell = nextRow.createCell(1);
                cell.setCellValue(map.get("day_all").toString());
                cell = nextRow.createCell(2);
                cell.setCellValue(map.get("day_confirm").toString());
                cell = nextRow.createCell(3);
                cell.setCellValue(map.get("day_alarm").toString());
            }

            String fileName = year_input+ "年"+ month_input +"报警记录总览.xls";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            book.write(os);
            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName).getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            byte[] buff = new byte[4096];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
            return MapRet.FILE_DOWNLOAD_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            logger.error("月记录导出错误：" + e);
            return MapRet.FILE_DOWNLOAD_ERROR();
        }
    }

    public Map<String, Object> getCountMap2(int year,int month,int day,String start,String end){
        try {
            int startUnix = new Long((new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(start + " 00:00:00").getTime() / 1000)).intValue();
            int endUnix =  new Long((new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(end + " 23:59:59").getTime() / 1000)).intValue();
            Integer day_alarm = alarmEventService.countByTimeRange(startUnix,endUnix);
            Integer day_confirm = alarmEventConfirmService.countByTimeRange(startUnix,endUnix);
            Map<String ,Object> stringObjectMap = new HashMap<String, Object>();
            stringObjectMap.put("day",year + "年" + month + "月" + day + "日");
            stringObjectMap.put("day_alarm" ,day_alarm);
            stringObjectMap.put("day_confirm",day_confirm);
            stringObjectMap.put("day_all",day_alarm + day_confirm);
            return stringObjectMap;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    public Map<String, Object> getCountMap(int month, String start, String end){
        try {
            int startUnix = new Long((new java.text.SimpleDateFormat("yyyy-MM-dd").parse(start).getTime() / 1000)).intValue();
            int endUnix =  new Long((new java.text.SimpleDateFormat("yyyy-MM-dd").parse(end).getTime() / 1000)).intValue();
            Integer month_alarm = alarmEventService.countByTimeRange(startUnix,endUnix);
            Integer month_confirm = alarmEventConfirmService.countByTimeRange(startUnix,endUnix);
            double month_rate;
            if((month_alarm + month_confirm) == 0) month_rate = 0;
            else month_rate = (double)month_confirm / (month_alarm + month_confirm);
            Map<String ,Object> stringObjectMap = new HashMap<String, Object>();
            stringObjectMap.put("month",month + "月");
            stringObjectMap.put("month_alarm" ,month_alarm);
            stringObjectMap.put("month_confirm",month_confirm);
            stringObjectMap.put("month_all",month_alarm + month_confirm);
            DecimalFormat df = new DecimalFormat("##.00");
            if(month_rate == 0) stringObjectMap.put("month_rate","0.00%");
            else stringObjectMap.put("month_rate",df.format(month_rate * 100) + "%");
            return stringObjectMap;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

}
